#  coding=utf-8
import hashlib

from werkzeug.security import generate_password_hash, check_password_hash

from .post import Post
from .. import db

from .base import BaseModel


class Club(BaseModel):
    __tablename__ = 'club'
    id = db.Column(db.BIGINT, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    introduction = db.Column(db.String(255), default='', doc='介绍')
    serial_number = db.Column(db.String(255), default='', doc='序列号')
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"), default=0, doc='作者')
    author = db.relationship('User', backref=db.backref('clubs'))
    password_hash = db.Column(db.String(255), default='', doc='密码')
    status = db.Column(db.SmallInteger, default=0, doc='状态')

    @staticmethod
    def generate_club():
        for i in range(2, 25):
            article = Club(name=u'第一俱乐部'+str(i),
                           introduction=u'第一俱乐部'+str(i),
                           author_id=1,
                           access_password="123456")
            db.session.add(article)
        db.session.commit()

    @staticmethod
    def insert_club(name, introduction, author_id, access_password):
        try:
            article = Club(name=name,
                           introduction=introduction,
                           author_id=author_id,
                           access_password=access_password)
            db.session.add(article)
            db.session.commit()
            return True, article
        except:
            return False, None

    @property
    def access_password(self):
        raise AttributeError('password is not a readable attribute')

    @access_password.setter
    def access_password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __init__(self, **kwargs):
        super(Club, self).__init__(**kwargs)

    def gravatar(self, size=40, default='identicon', rating='g'):
        url = 'http://gravatar.duoshuo.com/avatar'
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
            url=url, hash=hash, size=size, default=default, rating=rating)

    def __repr__(self):
        return '<Club %r>' % self.name
